/*
  * 识别文本类型，并把GBK格式转化为UTF-8
 */
package com.txt.gbk2utf;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class GbkToUtf {
	
	public String detectCodeFormat(String filePath) {
		String result = "";
		File file = new File(filePath);

		InputStream ios;
		try {
			ios = new java.io.FileInputStream(file);

			byte[] b = new byte[3];

			ios.read(b);
			ios.close();
			if (b[0] == -17 && b[1] == -69 && b[2] == -65)
				System.out.println(file.getName() + "：编码为UTF-8");
			else
				System.out.println(file.getName() + "：可能是GBK，也可能是其他编码。");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 判断文件的编码格式
	 * 
	 * @param fileName
	 *            :file
	 * @return 文件编码格式
	 * @throws Exception
	 */
	public static String codeString(String fileName) {
		String code = null;
		try {
			BufferedInputStream bin = new BufferedInputStream(
					new FileInputStream(fileName));
			int p = (bin.read() << 8) + bin.read();

			switch (p) {
			case 0xefbb:
				code = "UTF-8";
				break;
			case 0xfffe:
				code = "Unicode";
				break;
			case 0xfeff:
				code = "UTF-16BE";
				break;
			default:
				code = "GBK";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return code;
	}

	//重新编码
	public void recode(String filePath,String sourType,String desType){
		if(sourType.equals(desType)){
			System.out.println("格式正确，无须转化！");
			return;
		}
		String lineSeprator = System.getProperty("line.separator");
		StringBuffer sb = new StringBuffer();
		try{
			FileInputStream fInputStream = new FileInputStream(filePath);
			InputStreamReader isr = new InputStreamReader(fInputStream, sourType);
			//code为上面方法里返回的编码方式
			BufferedReader in = new BufferedReader(isr);
			
			String strTmp = "";
			//按行读取
			while (( strTmp = in.readLine()) != null) {
				sb.append(strTmp + lineSeprator);
			}
			
			fInputStream.close();
			isr.close();
			in.close();
			System.gc();
			
			//删除原文件
			File f = new File(filePath);
			
			boolean success = f.delete();
			if(!success){
				System.out.println("error：删除原文件失败！");
				return;
			}
			
			
			//按照desType所指示的编码来写如文件
			//此处false则从文件开头写起
			Writer wr = new OutputStreamWriter(new FileOutputStream(filePath,false),desType);
			wr.write(sb.toString());
			wr.close();
			
			
		}catch(Exception ex){
			ex.printStackTrace();
		}		
	}
	
		
	//转换
	public void convert(String path){
		File f = new File(path);
		if(!f.exists()){
			System.err.println("您所输入的文件或文件夹路径不存在！请重新输入!");
		}else{
			if (f.isDirectory()) {
				File[] filelist = f.listFiles();
				for (int i = 0; i < filelist.length; i++) {
					convert(filelist[i].getPath());
				}
			} else {// 如果不是目录，则直接处理该文件
				recode(path,codeString(path),"UTF-8");
			}
		}
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GbkToUtf gt = new GbkToUtf();
//		gt.detectCodeFormat("data/codestring.txt");
//		System.out.println(GbkToUtf.codeString("data/codestring.txt"));
		
		if(args.length != 1){
			System.out.println("请输入正确的参数(要转化的文件路径)!");
		}else{
//			System.out.println(codeString(args[0]));
			gt.convert(args[0]);
			System.out.println("转换完成!");
		}
		
			
//		testDeleteFile();

	}
	
	public static void testDeleteFile(){
		
		String filePath = "E:\\SVN\\SmallTools\\data\\src\\edu\\whu\\rose\\clock\\setup\\Analyze.java";//data/testdelete.txt";
		String lineSeprator = System.getProperty("line.separator");
		StringBuffer sb = new StringBuffer();
		try{
			FileInputStream fInputStream = new FileInputStream(filePath);
			InputStreamReader isr = new InputStreamReader(fInputStream, "GBK");
			//code为上面方法里返回的编码方式
			BufferedReader in = new BufferedReader(isr);
			
			String strTmp = "";
			//按行读取
			while (( strTmp = in.readLine()) != null) {
				sb.append(strTmp + lineSeprator);
			}
			in.close();
			isr.close();
			fInputStream.close();
			
			//删除原文件
			boolean success = (new File(filePath)).delete();
			if(!success){
				System.out.println("error：删除原文件失败！");
				return;
			}
			//按照desType所指示的编码来写如文件
			//此处false则从文件开头写起
			Writer wr = new OutputStreamWriter(new FileOutputStream(filePath,false),"UTF-8");
			wr.write(sb.toString());
			wr.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}	
	}

}
